#!/bin/sh

VPNUP='vpnup.sh'
VPNDOWN='vpndown.sh'
VPNLOG='/tmp/autoddvpn.log'
#PPTPSRVSUB=$(nvram get pptpd_client_srvsub)
DLDIR='http://autoddvpn.googlecode.com/svn/trunk/'
#CRONJOBS="* * * * * root /bin/sh /tmp/check.sh >> /tmp/last_check.log"
PID=$$
INFO="[INFO#${PID}]"
DEBUG="[DEBUG#${PID}]"
IPUP="/tmp/openvpncl/route-up.sh"
IPDOWN="/tmp/openvpncl/route-down.sh"
IPCONF="/tmp/openvpncl/openvpn.conf"


echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") log starts" >> $VPNLOG
echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") openvpn+jffs mode" >> $VPNLOG

echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") temporarily set date to 20100729 to fix openvpn SSL/TLS issue. see http://goo.gl/bb6a" >> $VPNLOG
#date 20100729
# fix issue #49 http://goo.gl/bvPUk
date -s "2010-07-29 12:00:00"

echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") modifying $IPUP" >> $VPNLOG

for i in 1 2 3 4 5 6 7 8 9 10 11 12
do
	if [ -e $IPUP ]; then
		#sed -ie 's#exit 0#/jffs/vpnup.sh\nexit 0#g' $IPUP
		echo '/jffs/openvpn/vpnup.sh openvpn' >> $IPUP
		echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") $IPUP modified" >> $VPNLOG
		break
	else
		echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") $IPUP not exists, sleep 10sec." >> $VPNLOG
		sleep 10
	fi
done

echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") modifying $IPDOWN" >> $VPNLOG
if [ -e $IPDOWN ]; then
	#sed -ie 's#exit 0#/jffs/vpndown.sh\nexit 0#g' $IPDOWN
	echo '/jffs/openvpn/vpndown.sh openvpn' >> $IPDOWN
	echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") $IPDOWN modified" >> $VPNLOG
else
	echo "$IPDOWN not exists" >> $VPNLOG
fi


echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") modifying $IPCONF" >> $VPNLOG
if [ -e $IPCONF ]; then
	cat $IPCONF > ${IPCONF}.bak
#	cat /jffs/openvpn/openvpn.conf >> ${IPCONF}.new
#	mv ${IPCONF}.new $IPCONF
	echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") $IPCONF modified" >> $VPNLOG
else
	echo "$IPCONF not exists" >> $VPNLOG
fi

echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") detect openvpn pid" >> $VPNLOG
#echo `ps` >> $VPNLOG
psline=`ps | grep openvpn | grep openvpncl`
pid=`echo $psline | cut -d" " -f1`
echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") openvpn pid=$pid" >> $VPNLOG
if test "x$pid" != "x"; then
	cmdline=`cat /proc/$pid/cmdline | tr '\000' ' '`
	kill -15 $pid
	sleep 2
	$cmdline
	echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") openvpn is running, restart it ( $cmdline )" >> $VPNLOG
else
	echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") openvpn is still not startup" >> $VPNLOG
fi
	
echo "$INFO $(date "+%d/%b/%Y:%H:%M:%S") ALL DONE. Let's wait for VPN being connected." >> $VPNLOG
